<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Cron {
	function Cron()
	{
		//$this->runStats();
		$this->refreshplaces();
		$this->generateNewList();
		$this->sendemails();
	}
	function runStats()
	{
		$CI =& get_instance();
		$data = array(
			"StatsIP" => $CI->input->ip_address(),
			"StatsUA" => $CI->input->user_agent(),
			"StatsDate" => time(),
			"StatsLoc" => $CI->uri->uri_string()
		);
		$CI->db->insert("stats", $data);
	}
	function generateNewList()
	{
		$CI =& get_instance();
		$t = new Place();
		$t->where("active", 1);
		$pobj = new Previousoption();
		$pobj->select_max("date");
		$pobj->limit(1);
		$pobj->get();
		$ts = time() - $pobj->date;
		//Our lunches happen every 7 days on thursday
		//so generate a new list every 7 days
		if ($ts > 604800 || $t->count() == 0) //6days
		{
			$places = new Place();
			$places->where("active", 0);
			$places->get();
			$lastplace_arr = explode(",", $pobj->options);
			$newplaces = array();
			foreach($places as $place)
				$newplaces[] = $place->id;
			$places = new Place();
			$places->update("active", 0);
			$randplaces = array_rand($newplaces, 5);
			$newplaceids = array();
			foreach($randplaces as $randplace)
			{
				$places = new Place();
				$place->get_by_id($newplaces[$randplace]);
				$newplaceids[] = $newplaces[$randplace];
				$place->active = 1;
				$place->save();
			}
			$pobj = new Previousoption();
			$pobj->options = implode(",", $newplaceids);
			$datearr = getdate();
			if ($datearr["wday"] < 4)
			{
				//Get thursday this week
				$delta = (4 - $datearr["wday"]);
			} else if ($datearr["wday"] > 4) {
				//Get thursday next week
				$delta = (4 - $datearr["wday"]) + 7;
			}
			$timestamp = time() + ($delta * 86400); //seconds in a day
			$numofdays = (6 - $datearr["wday"]) + (-$datearr["wday"]);
			$pobj->date = $timestamp;
			$pobj->save();
		}
	}
	function refreshplaces()
	{
		//get new places every month
		//determine a "months" time by getting the last 4 "previousoptions"
		//and comparing the months, if 4 same months, refresh places
		//also if there are less than 4 and places exist, then don't do anything
		
		//TODO: create table for blacklist and zipcode
		$placeobjs = new Place();
		$placeobjs->get();
		$previousobjs = new Previousoption();
		$previousobjs->select_max("date");
		$previousobjs->limit(5);
		$previousobjs->order_by("date", "desc");
		$previousobjs->get();
		$previousdates = array();
		$previousmonths = array();
		if ($previousobjs->count() > 4)
		{
			//check to see if we need to grab
			for($i = 0; $i <= 4; $i++)
				$previousdates[] = $previousobjs[$i]->date;
			
			foreach($previousdates as $previousdate)
			{
				$datearr = getdate($previousdate);
				$month = $datearr["month"];
				if (isset($previousmonths[$month]))
					$previousmonths[$month] += 1;
				else
					$previousmonths[$month] = 1;
			}
			foreach($previousmonths as $key=>$val)
			{
				if ($val == 4)
				{
					$placearrs = $this->getPlacesfromZip($zipcodeobj->zipcode);
					$this->addPlaces($placearrs);
				}
			}
			
		} else if ($previousobjs->count() <= 4 && $placeobjs->count() == 0) {
			//populate list
			$zipcodeobjs = new Zipcode();
			$zipcodeobjs->get();
			foreach($zipcodeobjs as $zipcodeobj)
			{
				$placearrs = $this->getPlacesfromZip($zipcodeobj->zipcode);
				$this->addPlaces($placearrs);
			}
		}
	}
	function getPlacesfromZip($zipcode)
	{
		$blacklistobjs = new Blacklist();
		$blacklistarr = array();
		$ret = array();
		foreach($blacklistobjs as $blacklistobj)
			$blacklistarr[] = $blacklistobj->place;
		$page = file_get_contents('http://www.urbanspoon.com/s/2?q=' . $zipcode);
		preg_match_all('/<div class="t">[\s]*(<a name="[A-Z]"\/\>)*[a-z0-9A-Z<=":\/.\- ]+>([A-Za-z0-9&; ]+)<\/a>/', 
							$page, $res);
		foreach($res as $p)
		{
			if (!in_array($p,$blacklistarr))
			{
				$ret[] = $p;
			}
		}
		return $p;
	}
	function addPlaces($placearr)
	{
		$currentplaceobjs = new Place();
		$currentplaceobjs->get();
		$currentplacearr = array();
		foreach($currentplaceobjs as $currentplaceobj)
			$currentplacearr[] = $currentplaceobj->place;
		foreach($placearr as $place)
		{
			if (!in_array($place, $currentplacearr))
			{
				$newplace = new Place();
				$newplace->place = $place;
				$newplace->active = 0;
				$newplace->save();
			}
		}
	}
	function sendemails()
	{
		$previousobjs = new Previousoption();
		$previousobjs->select_max("date");
		$previousobjs->limit(1);
		$previousobjs->get();
		$debug = false;
		if ((time() - $previousobjs->date) >= 86400 || $debug == true) //Is there about a day left? 
		{
			//Yes? Send an email with results
			$maxvote = new Vote();
			$maxvote->select("place_id, date, COUNT(place_id) AS c");
			$maxvote->where("date", $previousobjs->date);
			$maxvote->group_by("place_id");
			$maxvote->order_by("c", "DESC");
			$maxvote->limit(1);
			$maxvote->get();
			if ($maxvote->count() > 0)
			{
				$placeid = $maxvote->place_id;
				$placeobj = new Place();
				$placeobj->get_by_id($placeid);
				mail("adamsna@datanethost.net","Lunch - " . date("l F jS Y", $maxvote->date), "The restraunt will be: " . $placeobj->place);
			}
		}
	}
}
?>